# rt_host_machine_info.py
from flask import Blueprint, request, jsonify, render_template

from ..services import svc_host_machine_info
from ..models import DEFAULT_HOSTMACHINE_INFO_DATA
from ..utils.docker_operator_client import DockerOperatorClient
from ..utils.docker_operator_api import NetworkInfoDict
from requests import HTTPError

bp_host_machine_info = Blueprint(
    "host_machine_info", __name__, url_prefix="/host-machine-info"
)


@bp_host_machine_info.route("/create", methods=["POST"])
def create_host():
    data = request.get_json()
    name = data.get("name")
    description = data.get("description")
    address = data.get("address")
    host = svc_host_machine_info.create_host_machine_info(name, description, address)
    return (
        jsonify(
            {
                "id": host.id,
                "name": host.name,
                "description": host.description,
                "address": host.address,
            }
        ),
        201,
    )


@bp_host_machine_info.route("/<int:host_id>", methods=["GET"])
def get_host(host_id):
    host = svc_host_machine_info.get_host_machine_info_by_id(host_id)
    if not host:
        return jsonify({"error": "Host not found"}), 404
    return jsonify(
        {
            "id": host.id,
            "name": host.name,
            "description": host.description,
            "address": host.address,
        }
    )


@bp_host_machine_info.route("", methods=["GET"])
def get_all_hosts():
    hosts = svc_host_machine_info.get_all_host_machine_info()
    return jsonify(
        [
            {
                "id": host.id,
                "name": host.name,
                "description": host.description,
                "address": host.address,
                "status": svc_host_machine_info.get_host_machines_status_info().get(
                    host.id, DEFAULT_HOSTMACHINE_INFO_DATA
                ),
            }
            for host in hosts
        ]
    )


@bp_host_machine_info.route("/get_all_networks", methods=["GET"])
def get_all_networks():
    hosts = svc_host_machine_info.get_all_host_machine_info()
    cli = DockerOperatorClient(hosts[0].address)
    all_networks: dict[str, list[NetworkInfoDict]] = {}
    for host in hosts:
        try:
            all_networks[host.name] = cli.list_networks()
        except HTTPError as e:
            import traceback

            traceback.print_exc()
            pass
    return jsonify({"status": "success", "data": all_networks})


@bp_host_machine_info.route("/<int:host_id>", methods=["PUT"])
def update_host(host_id):
    data = request.get_json()
    name = data.get("name")
    description = data.get("description")
    address = data.get("address")
    host = svc_host_machine_info.update_host_machine_info(
        host_id, name, description, address
    )
    if not host:
        return jsonify({"error": "Host not found"}), 404
    return jsonify(
        {
            "id": host.id,
            "name": host.name,
            "description": host.description,
            "address": host.address,
        }
    )


@bp_host_machine_info.route("/<int:host_id>", methods=["DELETE"])
def delete_host(host_id):
    success = svc_host_machine_info.delete_host_machine_info(host_id)
    if not success:
        return jsonify({"error": "Host not found"}), 404
    return jsonify({"message": "Host deleted successfully"}), 200


# 新增路由以渲染 host_machines.html
@bp_host_machine_info.route("/view", methods=["GET"])
def view_hosts():
    return render_template("host_machines.html")


@bp_host_machine_info.route("/export_table", methods=["GET"])
def export_table():
    csv_data = svc_host_machine_info.export_host_machine_info_to_csv()
    return (
        csv_data,
        200,
        {
            "Content-Type": "text/csv",
            "Content-Disposition": "attachment; filename=host_machines.csv",
        },
    )


@bp_host_machine_info.route("/import_table", methods=["POST"])
def import_table():
    if "file" not in request.files:
        return jsonify({"error": "No file part"}), 400
    file = request.files["file"]
    if file.filename == "":
        return jsonify({"error": "No selected file"}), 400
    if file and file.filename and file.filename.endswith(".csv"):
        csv_data = file.read().decode("utf-8")
        try:
            svc_host_machine_info.import_host_machine_info_from_csv(csv_data)
            return jsonify({"message": "Data imported successfully"}), 200
        except Exception as e:
            return jsonify({"error": str(e)}), 400
    else:
        return jsonify({"error": "Invalid file type"}), 400
